'use client'
import { useState } from 'react'
import { useWeb3 } from '@/hooks/useWeb3'
import { ethers } from 'ethers'

export default function Home() {
  const { account, bankContract, tokenContract, connectWallet } = useWeb3()
  const [amount, setAmount] = useState('')
  const [recipient, setRecipient] = useState('')
  const [balance, setBalance] = useState('0')

  const handleDeposit = async () => {
    try {
      if (!tokenContract || !bankContract) return
      const amountWei = ethers.utils.parseEther(amount)

      
      // 检查代币余额
      const balance = await tokenContract.balanceOf(account)
      console.log('当前代币余额:', ethers.utils.formatEther(balance))
      
      // 检查授权额度
      const allowance = await tokenContract.allowance(account, bankContract.address)
      console.log('当前授权额度:', ethers.utils.formatEther(allowance))
      
      // 如果授权额度不足，先进行授权
      if (allowance.lt(amountWei)) {
        console.log('正在授权...')
        const approveTx = await tokenContract.approve(bankContract.address, amountWei)
        await approveTx.wait()
        console.log('授权成功')
      }
      
      // 执行存款
      console.log('正在存款...')
      const tx = await bankContract.deposit(amount)
      await tx.wait()
      alert('存款成功！')
    } catch (error: any) {
      console.error('存款失败:', error)
      
      // 改进错误处理
      if (error.data) {
        try {
          // 尝试解码合约错误
          const decodedError = bankContract?.interface.parseError(error.data)
          console.log('解码后的错误:', decodedError)
          alert(`存款失败: ${decodedError?.name || error.message}`)
        } catch (e) {
          console.log('无法解码错误:', error.data)
          alert(`存款失败: ${error.message}`)
        }
      } else {
        alert(`存款失败: ${error.message}`)
      }
    }
  }

  const handleWithdraw = async () => {
    try {
      if (!bankContract) return
      await bankContract.withdraw(amount)
      alert('取款成功！')
    } catch (error) {
      console.error(error)
      alert('取款失败！')
    }
  }

  const handleTransfer = async () => {
    try {
      if (!bankContract) return
      await bankContract.bankTransfer(recipient, amount)
      alert('转账成功！')
    } catch (error) {
      console.error(error)
      alert('转账失败！')
    }
  }

  const checkBalance = async () => {
    try {
      if (!bankContract) return
      console.log('合约实例：', bankContract)
      console.log('可用方法：', Object.keys(bankContract.functions))
      const balance = await bankContract.myBalance()
      setBalance(balance.toString())
    } catch (error) {
      console.error(error)
    }
  }

  // 添加一个辅助函数来格式化地址
  const formatAddress = (address: string) => {
    if (!address) return '';
    return `${address.slice(0, 6)}...${address.slice(-4)}`;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md mx-auto bg-white rounded-xl shadow-lg p-8 border border-gray-100">
        <h1 className="text-3xl font-bold mb-8 text-center bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-purple-600">
          Alan-Bank
        </h1>
        
        <div className="mb-8">
          {account ? (
            <div className="space-y-3">
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-gray-700 text-sm mb-1">当前账户</p>
                <p className="text-gray-900 font-mono">{formatAddress(account)}</p>
              </div>
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-gray-700 text-sm mb-1">账户余额</p>
                <p className="text-2xl font-semibold text-gray-900">{balance}</p>
              </div>
              <button 
                onClick={checkBalance}
                className="w-full bg-gradient-to-r from-blue-500 to-blue-600 text-white py-2.5 px-4 rounded-lg
                  hover:from-blue-600 hover:to-blue-700 transition duration-200 font-medium"
              >
                刷新余额
              </button>
            </div>
          ) : (
            <button
              onClick={connectWallet}
              className="w-full bg-gradient-to-r from-purple-500 to-blue-500 text-white py-3 px-4 rounded-lg
                hover:from-purple-600 hover:to-blue-600 transition duration-200 font-medium"
            >
              连接钱包
            </button>
          )}
        </div>

        {account && (
          <div className="space-y-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                金额
              </label>
              <input
                type="text"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                placeholder="请输入金额"
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 
                  focus:border-blue-500 transition duration-200"
              />
            </div>

            <div className="flex gap-4">
              <button
                onClick={handleDeposit}
                className="flex-1 bg-gradient-to-r from-emerald-500 to-green-500 text-white py-3 rounded-lg
                  hover:from-emerald-600 hover:to-green-600 transition duration-200 font-medium"
              >
                存款
              </button>
              <button
                onClick={handleWithdraw}
                className="flex-1 bg-gradient-to-r from-red-500 to-rose-500 text-white py-3 rounded-lg
                  hover:from-red-600 hover:to-rose-600 transition duration-200 font-medium"
              >
                取款
              </button>
            </div>

            <div className="pt-4 border-t border-gray-200">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                收款地址
              </label>
              <input
                type="text"
                value={recipient}
                onChange={(e) => setRecipient(e.target.value)}
                placeholder="请输入收款地址"
                className="w-full p-3 border border-gray-300 rounded-lg mb-4 focus:ring-2 
                  focus:ring-purple-500 focus:border-purple-500 transition duration-200"
              />
              <button
                onClick={handleTransfer}
                className="w-full bg-gradient-to-r from-purple-500 to-indigo-500 text-white py-3 rounded-lg
                  hover:from-purple-600 hover:to-indigo-600 transition duration-200 font-medium"
              >
                转账
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}